<template>
  <div class="deploy-list p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">部署列表</h2>
          <div class="flex gap-2">
            <el-button type="primary" @click="goToLocalDeploy">本地文件部署</el-button>
            <el-button type="primary" @click="goToCreate">创建部署</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container mb-4 flex flex-wrap items-center gap-4">
        <el-input
          v-model="queryParams.projectName"
          placeholder="项目名称"
          class="w-64"
          clearable
          @clear="handleQuery"
        />
        
        <el-select v-model="queryParams.environment" placeholder="部署环境" clearable @change="handleQuery" class="w-32">
          <el-option label="开发环境" :value="DeployEnvironment.DEVELOPMENT" />
          <el-option label="测试环境" :value="DeployEnvironment.TESTING" />
          <el-option label="生产环境" :value="DeployEnvironment.PRODUCTION" />
        </el-select>
        
        <el-select v-model="queryParams.status" placeholder="部署状态" clearable @change="handleQuery" class="w-32">
          <el-option label="待部署" :value="DeployStatus.PENDING" />
          <el-option label="部署中" :value="DeployStatus.PROCESSING" />
          <el-option label="成功" :value="DeployStatus.SUCCESS" />
          <el-option label="失败" :value="DeployStatus.FAILED" />
        </el-select>
        
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="deployList"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="projectName" label="项目名称" width="180" show-overflow-tooltip />
        <el-table-column label="部署环境" width="120">
          <template #default="{ row }">
            <el-tag :type="getEnvironmentTag(row.environment)">
              {{ getEnvironmentName(row.environment) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本号" width="120" />
        <el-table-column label="部署状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="部署进度" width="200">
          <template #default="{ row }">
            <el-progress
              :percentage="calculateProgress(row)"
              :status="getProgressStatus(row.status)"
              :format="progressFormat"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="goToDetail(row.id)">详情</el-button>
            <el-button 
              v-if="row.status === DeployStatus.FAILED" 
              type="warning" 
              link 
              @click="handleRetry(row)"
            >重试</el-button>
            <el-button 
              v-if="row.status === DeployStatus.PENDING || row.status === DeployStatus.PROCESSING" 
              type="danger" 
              link 
              @click="handleCancel(row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDeployList, cancelDeploy, retryDeploy } from '@/request/deploy-api'
import { DeployEnvironment, DeployStatus, type DeployRecord } from '@/model/deploy-model'
import type { PageQuery } from '@/model/common-model'

defineOptions({
  name: 'DeployList'
})

const router = useRouter()
const loading = ref(false)
const deployList = ref<DeployRecord[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<PageQuery>({
  page: 1,
  page_size: 10,
  projectName: '',
  environment: undefined,
  status: undefined
})

// 获取部署列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getDeployList(queryParams)
    if (response.code === 0) {
      // 处理不同的响应格式
      if (Array.isArray(response.data)) {
        // 直接是数组
        deployList.value = response.data
        total.value = response.data.length || 0
      } else if (response.data && 'list' in response.data) {
        // 包含 list 和 total 的格式
        deployList.value = (response.data as any).list || []
        total.value = (response.data as any).total || 0
      } else if (response.data && 'items' in response.data) {
        // 包含 items 的格式
        deployList.value = (response.data as any).items || []
        total.value = (response.data as any).total || (response.data as any).items?.length || 0
      } else {
        deployList.value = []
        total.value = 0
      }
    } else {
      ElMessage.error(response.errorMsg || '获取部署列表失败')
    }
  } catch (error) {
    console.error('获取部署列表失败:', error)
    ElMessage.error('获取部署列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.page = 1
  queryParams.projectName = ''
  queryParams.environment = undefined
  queryParams.status = undefined
  getList()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryParams.page_size = val
  getList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  queryParams.page = val
  getList()
}

// 获取环境标签类型
const getEnvironmentTag = (environment: DeployEnvironment) => {
  switch (environment) {
    case DeployEnvironment.DEVELOPMENT:
      return 'info'
    case DeployEnvironment.TESTING:
      return 'warning'
    case DeployEnvironment.PRODUCTION:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取环境名称
const getEnvironmentName = (environment: DeployEnvironment) => {
  switch (environment) {
    case DeployEnvironment.DEVELOPMENT:
      return '开发环境'
    case DeployEnvironment.TESTING:
      return '测试环境'
    case DeployEnvironment.PRODUCTION:
      return '生产环境'
    default:
      return environment
  }
}

// 获取状态标签类型
const getStatusTag = (status: DeployStatus) => {
  switch (status) {
    case DeployStatus.SUCCESS:
      return 'success'
    case DeployStatus.PROCESSING:
      return 'warning'
    case DeployStatus.PENDING:
      return 'info'
    case DeployStatus.FAILED:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态名称
const getStatusName = (status: DeployStatus) => {
  switch (status) {
    case DeployStatus.SUCCESS:
      return '成功'
    case DeployStatus.PROCESSING:
      return '部署中'
    case DeployStatus.PENDING:
      return '待部署'
    case DeployStatus.FAILED:
      return '失败'
    default:
      return status
  }
}

// 计算部署进度
const calculateProgress = (deploy: DeployRecord) => {
  if (!deploy.steps || deploy.steps.length === 0) return 0
  
  const totalSteps = deploy.steps.length
  const completedSteps = deploy.steps.filter(
    step => step.status === DeployStatus.SUCCESS
  ).length
  
  if (deploy.status === DeployStatus.SUCCESS) return 100
  if (deploy.status === DeployStatus.FAILED) {
    // 如果失败，计算到失败步骤的进度
    const failedStepIndex = deploy.steps.findIndex(step => step.status === DeployStatus.FAILED)
    if (failedStepIndex >= 0) {
      return Math.round((failedStepIndex / totalSteps) * 100)
    }
  }
  
  return Math.round((completedSteps / totalSteps) * 100)
}

// 获取进度条状态
const getProgressStatus = (status: DeployStatus) => {
  switch (status) {
    case DeployStatus.SUCCESS:
      return 'success'
    case DeployStatus.PROCESSING:
      return ''
    case DeployStatus.PENDING:
      return ''
    case DeployStatus.FAILED:
      return 'exception'
    default:
      return ''
  }
}

// 进度条格式化
const progressFormat = (percentage: number) => {
  return percentage === 100 ? '完成' : `${percentage}%`
}

// 跳转到创建页面
const goToCreate = () => {
  router.push('/deploy/create')
}

// 跳转到本地部署页面
const goToLocalDeploy = () => {
  router.push('/deploy/local')
}

// 跳转到详情页面
const goToDetail = (id: string) => {
  router.push(`/deploy/detail/${id}`)
}

// 处理重试
const handleRetry = (row: DeployRecord) => {
  ElMessageBox.confirm(`确认重试部署 "${row.projectName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await retryDeploy(row.id)
        if (response.code === 0) {
          ElMessage.success('重试操作已提交')
          getList()
        } else {
          ElMessage.error(response.errorMsg || '重试失败')
        }
      } catch (error) {
        console.error('重试部署失败:', error)
        ElMessage.error('重试部署失败')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 处理取消
const handleCancel = (row: DeployRecord) => {
  ElMessageBox.confirm(`确认取消部署 "${row.projectName}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await cancelDeploy(row.id)
        if (response.code === 0) {
          ElMessage.success('已取消部署')
          getList()
        } else {
          ElMessage.error(response.errorMsg || '取消失败')
        }
      } catch (error) {
        console.error('取消部署失败:', error)
        ElMessage.error('取消部署失败')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.deploy-list {
  .pagination-container {
    padding: 10px 0;
  }
}
</style>
